package a_doubleWrite;

import util.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * 105. 从前序与中序遍历序列构造二叉树
 *
 * @author: luolidong
 * @create: 2021-07-24 10:05
 * @version: 1.0
 */
public class L105 {
    Map<Integer, Integer> map;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        //记录中序位置
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        //递归
        return dfs(preorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    private TreeNode dfs(int[] preorder, int preLeft, int preRight, int inLeft, int inRight) {
        if (preLeft > preRight || inLeft > inRight) return null;
        int rootVal = preorder[preLeft];
        int inMid = map.get(rootVal);
        TreeNode root = new TreeNode(rootVal);
        root.left = dfs(preorder, preLeft + 1, preRight + inMid - inRight, inLeft, inMid - 1);
        root.right = dfs(preorder, preRight + inMid - inRight + 1, preRight, inMid + 1, inRight);
        return root;

    }
}
